/**
 * 插件管理模块
 * 系统模块，集成在内部、无法安装卸载
 * @version 0.0.1
 * @time 2016年3月7日11:07:41
 * @author maomaohou
 */
define(["jquery","juicer","core/util"],function($,j,util){
	
	window.__util=util;
	
	var View={
		
		createView:function(){
			var $div = $("<div/>").appendTo($("body"));
			$div.window({
				width: 720,
				height: 480,
				title: "插件管理",
				minimizable: false,
				collapsible: false,
				maximizable:false,
				resizable:false,
				modal: true,
				cache:false,
				shadow:false,
				href:"/res/views/plugMgrView.html",
				openAnimation: "slide",
				onLoad: function() {
					View.initView();
				},
				onClose: function() {
					$div.window("destroy", true);
				}
			});
		},
		
		initView:function(){
			onDragUp($("#upload"));
			var d = $("#plugin-store-grid");
			d.datagrid({
				fit:true,
				singleSelect:true,
				method:"get",
				fitColumns: true,
				url: "/sys/ol/plu",
				onLoadSuccess: function(data) {},
				columns: [
					[{
						field: 'name',
						title: '插件名称',
						width: 100
					}, {
						field: 'author',
						title: '开发人员',
						width: 100
					}, {
						field: 'version',
						title: '版本',
						width: 100
					}, {
						field: 'email',
						title: '联系方式',
						width: 100
					}, {
						field: 'op',
						title: '操作',
						width: 100,
						formatter:function(v,r,i){
							return "<a href='javascript:;' name='"+r.name+"' onClick='__util.down(this);'>安装</a>"
						}
					}]
				]

			})
		}
		
	}
	
	function onDragUp(selector) {
			selector.on("drop", function(event) {
				event.preventDefault();
				var bar=selector.find("div"); 
				var files = event.originalEvent.dataTransfer.files;
				if (files.length > 0) {
					if (files[0].name.indexOf('.zip') === -1) {
						util.toast("请选择zip格式文件上传","error")
						return false;
					}
					var _file = files[0];
					var fd = new FormData();
					fd.append("ufile", _file);
					var xhr = new XMLHttpRequest();
					xhr.open("post", "/sys/plu/upload", true);
					xhr.upload.addEventListener("progress", function(e) {
						//计算上传进度
						if (e.lengthComputable) {
							var percentage = Math.round((e.loaded * 100) / e.total);
							bar.css("width",percentage+"%");
							if(percentage==100){
								bar.html("上传完毕正在解压...");
							}
						}
					}, false);
					xhr.addEventListener("load", function() {
						var a = JSON.parse(xhr.responseText);
						if(a.code==0){
							util.toast("上传成功");
							bar.html("").css("width",0);
							$("#plugin-grid").datagrid("reload");
						}
					});
					xhr.send(fd);
				}
			})
		}
	
	return {
		run:View.createView
	}
	
})
